package com.main.by.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.main.by.entity.vo.CateVO;
import com.main.by.entity.vo.TaskVO;
import com.main.by.exception.ServiceException;
import com.main.by.service.CateService;
import com.main.by.service.TaskService;
import com.main.by.service.UploadFileService;
import com.main.by.util.StringUtil;

@Controller
@RequestMapping("/adminjsp/")
public class TaskController {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private CateService cateService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private UploadFileService uploadFileService;
	
	@RequestMapping(value = "addTask", method = RequestMethod.GET)
	public String addTask(HttpServletRequest request){
		logger.info("查看所有分类信息-------");
		try {
			List<CateVO> cateInfo = cateService.findAllCate(request);
			request.getSession().setAttribute("taskCateInfoList", cateInfo);
		}catch (ServiceException serviceE){
			return "adminjsp/index";
		}catch (Exception e) {
			logger.error("select news failed! ", e);
			return "adminjsp/index";
		}
		return "adminjsp/addTask";
	}
	
	@RequestMapping(value = "addNewTaskInfo", method = RequestMethod.POST)
	@ResponseBody
	public void addNewTaskInfo(HttpServletRequest request,HttpServletResponse response,@RequestParam("minPic") MultipartFile file1,@RequestParam("maxPic") MultipartFile file2) throws IOException{
		TaskVO taskInfo = new TaskVO();
		PrintWriter out = response.getWriter();
		logger.info("taskUpload info:");
		boolean flag = false;
		//errorMessage：上传失败，则是错误信息；上传成功，则提示成功以及显示文件上传后的地址
		String errorMessage = "";  
		try{
			String destinationDir ="G:/byProject/byProject/webapp/taskUploadFile/";
			List<MultipartFile> file = new ArrayList<MultipartFile>();
			file.add(file1);
			file.add(file2);
			String writeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			String taskTitle = request.getParameter("title");
			String count = request.getParameter("count");
			String taskDesc = request.getParameter("taskDesc");
			String content = request.getParameter("content");
			String categId = request.getParameter("categId");
			taskInfo.setCount(count);
			taskInfo.setContent(content);
			taskInfo.setFlag("0");
			taskInfo.setTaskDate(writeDate);
			taskInfo.setCateId(categId);
			taskInfo.setTaskDesc(taskDesc);
			taskInfo.setTitle(taskTitle);
			if (file.size() >= 2) {
				//获得文件的后缀名
				String file1Type = file.get(0).getContentType();
				String name1Type = file1Type.substring(file1Type.indexOf("/")+1,file1Type.length());
				String file2Type = file.get(1).getContentType();
				String name2ype = file2Type.substring(file2Type.indexOf("/")+1,file2Type.length());
				if (("jpg".equals(name1Type) ||"bmp".equals(name1Type) || "gif".equals(name1Type) || "jpeg".equals(name1Type)) &&
						("jpg".equals(name2ype) || "bmp".equals(name2ype) || "gif".equals(name2ype) || "jpeg".equals(name2ype)) ){
					String fileName1Type = file.get(0).getOriginalFilename();
					String fileName2Type = file.get(1).getOriginalFilename();
					String fileName1 = getFileName()+"1"+fileName1Type.substring(fileName1Type.indexOf("."),fileName1Type.length()); 
					String fileName2 = getFileName()+"2"+fileName2Type.substring(fileName2Type.indexOf("."),fileName2Type.length()); 
					taskInfo.setMinPic(fileName1);
					taskInfo.setMaxPic(fileName2);
					flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,fileName2);
					if (flag) {
						flag = taskService.addTaskInfo(taskInfo, request, response);
					} else {
						//上传失败，返回到前台
						out
						.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
					}
					
				} else {
					out
					.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
				}
			}
		}catch (ServiceException serviceE){
			logger.error("firstUpload failed!" , serviceE);
			errorMessage = serviceE.getMessage();
		}catch (Exception e){
			logger.error("firstUpload failed!" , e);
			errorMessage = "新增文件失败!";
		}
		if(flag){
		    //上传成功，返回到前台
			response.sendRedirect("taskList");
		} else {
			//上传失败，返回到前台
			out
			.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
		}
	}
	
	
	@RequestMapping(value = "taskList", method = RequestMethod.GET)
	public String taskList(HttpServletRequest request){
		logger.info("查看所有新闻信息-------");
		try {
			List<TaskVO> taskInfo = taskService.findAllTask(request);
			List<CateVO> cateInfo = cateService.findAllCate(request);
			request.getSession().setAttribute("taskCateInfoList", cateInfo);
			request.getSession().setAttribute("adminTaskInfList", taskInfo);
		}catch (ServiceException serviceE){
			return "adminjsp/index";
		}catch (Exception e) {
			logger.error("select news failed! ", e);
			return "adminjsp/index";
		}
		return "adminjsp/taskList";
	}

	@RequestMapping(value = "modifyTask", method = RequestMethod.GET)
	public String modifyTask(HttpServletRequest request) throws IOException{
		String errorMessage = "修改失败";
		String taskId =  request.getParameter("taskId");
		int id = 0;
		if (StringUtil.isNotBlank(taskId)) {
			id = Integer.parseInt(taskId);
		}
		logger.info("根据ID查找新闻信息-------");
		TaskVO taskInfo = new TaskVO();
		String cateName = "";
		try {
			taskInfo = taskService.findTaskById(id);
			List<CateVO> cateifo = (ArrayList<CateVO>) request.getSession().getAttribute("taskCateInfoList");
			if (cateifo != null && cateifo.size() > 0) {
				for (int i = 0; i < cateifo.size(); i++) {
					if (taskInfo.getCateId().equals(cateifo.get(i).getCateId())) {
						cateName = cateifo.get(i).getCateName();
						request.getSession().setAttribute("cateName", cateName);
					}
				}
			}  else {
				List<CateVO> cateInfoList = cateService.findAllCate(request);
				request.getSession().setAttribute("taskCateInfoList", cateInfoList);
				for (int i = 0; i < cateInfoList.size(); i++) {
					if (taskInfo.getCateId().equals(cateInfoList.get(i).getCateId())) {
						cateName = cateInfoList.get(i).getCateName();
						request.getSession().setAttribute("cateName", cateName);
					}
				}
			}
			request.getSession().setAttribute("updateTaskInfo", taskInfo);
		}catch (ServiceException serviceE){
			errorMessage = serviceE.getMessage();
			return "adminjsp/taskList";
		}catch (Exception e) {
			logger.error("select admin failed! ", e);
			return "adminjsp/taskList";
		}
		return "adminjsp/modifyTask";
	}
	
	@RequestMapping(value = "deleteTask", method = RequestMethod.GET)
	public void deleteTask(HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.setCharacterEncoding("utf8");
		response.setContentType("text/html;charset=utf8");
		String taskId =  request.getParameter("taskId");
		PrintWriter out = response.getWriter();
		int id = 0;
		if (StringUtil.isNotBlank(taskId)) {
			id = Integer.parseInt(taskId);
		}
		logger.info("根据ID查找管理员信息-------");
		try {
			taskService.deleteTaskById(id);
			response.sendRedirect("taskList");
		}catch (ServiceException serviceE){
			out
			.print("<script type='text/javascript'>alert('删除失败');history.go(-1);</script>");
		}catch (Exception e) {
			logger.error("select admin failed! ", e);
			out
			.print("<script type='text/javascript'>alert('删除失败');history.go(-1);</script>");
		}
		
	}
	
	@RequestMapping(value = "saveTaskInfo", method = RequestMethod.POST)
	@ResponseBody
	public void saveTaskInfo(HttpServletRequest request,HttpServletResponse response,@RequestParam("minPic") MultipartFile file1,@RequestParam("maxPic") MultipartFile file2) throws IOException{
		TaskVO taskInfo = new TaskVO();
		PrintWriter out = response.getWriter();
		logger.info("taskUpload info:");
		boolean flag = false;
		//errorMessage：上传失败，则是错误信息；上传成功，则提示成功以及显示文件上传后的地址
		String errorMessage = "";  
		try{
			String destinationDir ="G:/byProject/byProject/webapp/taskUploadFile/";
			List<MultipartFile> file = new ArrayList<MultipartFile>();
			if (file1.getSize() > 0) {
				file.add(file1);
			}
			if (file2.getSize() > 0) {
				file.add(file2);
			}
			String writeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			String taskId = request.getParameter("taskId");
			String taskTitle = request.getParameter("title");
			String count = request.getParameter("count");
			String taskDesc = request.getParameter("taskDesc");
			String content = request.getParameter("content");
			String categId = request.getParameter("categId");
			String oldMinPic = request.getParameter("oldMinPic");
			String oldMaxPic = request.getParameter("oldMaxPic");
			taskInfo.setTaskId(taskId);
			taskInfo.setCount(count);
			taskInfo.setContent(content);
			taskInfo.setFlag("0");
			taskInfo.setTaskDate(writeDate);
			taskInfo.setCateId(categId);
			taskInfo.setTaskDesc(taskDesc);
			taskInfo.setTitle(taskTitle);
			if (file.size() >= 2) {
				//获得文件的后缀名
				String file1Type = file.get(0).getContentType();
				String name1Type = file1Type.substring(file1Type.indexOf("/")+1,file1Type.length());
				String file2Type = file.get(1).getContentType();
				String name2ype = file2Type.substring(file2Type.indexOf("/")+1,file2Type.length());
				if (("jpg".equals(name1Type) ||"bmp".equals(name1Type) || "gif".equals(name1Type) || "jpeg".equals(name1Type)) &&
						("jpg".equals(name2ype) || "bmp".equals(name2ype) || "gif".equals(name2ype) || "jpeg".equals(name2ype)) ){
					String fileName1Type = file.get(0).getOriginalFilename();
					String fileName2Type = file.get(1).getOriginalFilename();
					String fileName1 = getFileName()+"1"+fileName1Type.substring(fileName1Type.indexOf("."),fileName1Type.length()); 
					String fileName2 = getFileName()+"2"+fileName2Type.substring(fileName2Type.indexOf("."),fileName2Type.length()); 
					taskInfo.setMinPic(fileName1);
					taskInfo.setMaxPic(fileName2);
					flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,fileName2);
					if (flag) {
						flag = taskService.saveTaskInfo(taskInfo);
					} else {
						//上传失败，返回到前台
						out
						.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
					}
					
				} else {
					out
					.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
				}
			} else if (file.size() >= 1){
				if (file1.getSize() > 0) {
					//获得文件的后缀名
					String file1Type = file.get(0).getContentType();
					String name1Type = file1Type.substring(file1Type.indexOf("/")+1,file1Type.length());
					if (("jpg".equals(name1Type) ||"bmp".equals(name1Type) || "gif".equals(name1Type) || "jpeg".equals(name1Type))){
						String fileName1Type = file.get(0).getOriginalFilename();
						String fileName1 = getFileName()+"1"+fileName1Type.substring(fileName1Type.indexOf("."),fileName1Type.length()); 
						String fileName2 = oldMaxPic;
						taskInfo.setMinPic(fileName2);
						taskInfo.setMaxPic(fileName1);
						flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,fileName2);
						if (flag) {
							flag = taskService.saveTaskInfo(taskInfo);
						} else {
							//上传失败，返回到前台
							out
							.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
						}
						
					} else {
						out
						.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
					}
				} else {
					//获得文件的后缀名
					String file2Type = file.get(0).getContentType();
					String name2Type = file2Type.substring(file2Type.indexOf("/")+1,file2Type.length());
					if (("jpg".equals(name2Type) ||"bmp".equals(name2Type) || "gif".equals(name2Type) || "jpeg".equals(name2Type))){
						String fileName2Type = file.get(0).getOriginalFilename();
						String fileName1 = getFileName()+"1"+fileName2Type.substring(fileName2Type.indexOf("."),fileName2Type.length()); 
						String fileName2 = oldMinPic;
						taskInfo.setMinPic(fileName2);
						taskInfo.setMaxPic(fileName1);
						flag = uploadFileService.uploadHandoutImg(destinationDir,  file, fileName1,fileName2);
						if (flag) {
							flag = taskService.saveTaskInfo(taskInfo);
						} else {
							//上传失败，返回到前台
							out
							.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
						}
						
					} else {
						out
						.print("<script type='text/javascript'>alert('不是标准的图片文件')</script>");
					}
				}
			} 
			if (file.size() <= 0 ) {
					//获得文件的后缀名
					String  fileName1 = oldMinPic;
					String  fileName2 = oldMaxPic;
					taskInfo.setMinPic(oldMinPic);
					taskInfo.setMaxPic(oldMaxPic);
					flag = taskService.saveTaskInfo(taskInfo);
				} 
		}catch (ServiceException serviceE){
			logger.error("firstUpload failed!" , serviceE);
			errorMessage = serviceE.getMessage();
		}catch (Exception e){
			logger.error("firstUpload failed!" , e);
			errorMessage = "新增文件失败!";
		}
		if(flag){
		    //上传成功，返回到前台
			response.sendRedirect("taskList");
		} else {
			//上传失败，返回到前台
			out
			.print("<script type='text/javascript'>alert('上传失败');history.go(-1);</script>");
		}
	}
	
	
	private String getFileName() {
		//根据时间产生文件名
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmssms");
		return df.format(new Date());
	}

}
